<template>
  <div class="update-photo">
    <img :src="img"
         ref="img"
         class="img">
    <div class="toolbar">
      <span @click="$emit('close')">取消</span>
      <span class="isOk"
            @click="onConfirm">完成</span>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updateUserPhoto } from '@/api/user.js'
export default {
  name: 'UpdatePhoto',
  props: {
    img: {
      type: [String, Object],
      required: true
    }
  },
  data () {
    return {
      cropper: null
    }
  },
  mounted () {
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false
    })
    // console.log(this.cropper)
  },
  methods: {
    onConfirm () {
      this.cropper.getCroppedCanvas().toBlob(blob => {
        // console.log(blob)
        this.updateUserPhoto(blob)
      })
    },
    async updateUserPhoto (blob) {
      this.$toast.loading({
        message: '保存中...',
        forbidClick: true,
        duration: 0
      })
      try {
        const formData = new FormData()
        formData.append('photo', blob)
        const { data } = await updateUserPhoto(formData)
        this.$emit('close')
        this.$emit('update-photo', data.data.photo)
        this.$toast.success('更新成功')
      } catch (err) {
        this.$toast.fail('更新失败！')
      }
    }
  }
}
</script>

<style lang="less" scoped >
.update-photo {
  background-color: #000 !important;
  height: 100%;
  widows: 100%;
  img {
    width: 100%;
    margin-top: 300px;
  }
  .toolbar {
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    color: #fff;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    padding: 15px;
    font-size: 18px;
    .isOk {
      float: right;
      margin-right: 30px;
    }
  }
}
</style>
